! ALCF: extracted from main

! ALCF: coor version called only from usdefn
subroutine alcf_coor( esm, es, a )
implicit none

real(8), dimension(3), intent( in )  :: esm
real(8), intent( out ) :: es( 3 ), a( 3,3 )
    
real(8) r,emin,e(3)
real(8) x,y,z
integer i,imin,imin1,imin2

es( 1:3 ) = esm( 1:3 ) / dsqrt( esm(1) * esm(1) + esm(2) * esm(2) + esm(3) * esm(3) )

e(1) = es(1)
e(2) = es(2)
e(3) = es(3)

!r=dsqrt(e(1)**2+e(2)**2+e(3)**2) ! NOTE: the second time of normalization, VSemiletov
r = dsqrt( e(1) * e(1) + e(2) * e(2) + e(3) * e(3) )

a(1,1) = e(1) / r
a(2,1) = e(2) / r
a(3,1) = e(3) / r

emin=1e10
imin=0
do i=1,3
    if (emin.gt.dabs(e(i))) then
        emin=dabs(e(i))
        imin=i
        if (abs(emin).lt.1d-10) then 
            a(1,2)=0.0
            a(2,2)=0.0
            a(3,2)=0.0
            a(imin,2)=1.0d0
            goto 1
        end if	
    end if
end do

imin1=imin+1
if (imin1.gt.3) imin1=1
imin2=imin1+1
if (imin2.gt.3) imin2=1

e(imin)=0.0d0
r=e(imin1)
e(imin1)=-e(imin2)
e(imin2)=r
r=dsqrt(e(imin1)**2+e(imin2)**2)

a(1,2) = e(1) / r
a(2,2) = e(2) / r
a(3,2) = e(3) / r

1 continue

a( 1,3 ) = a( 2,1 ) * a( 3,2 ) - a( 3,1 ) * a( 2,2 )
a( 2,3 ) = a( 3,1 ) * a( 1,2 ) - a( 1,1 ) * a( 3,2 )
a( 3,3 ) = a( 1,1 ) * a( 2,2 ) - a( 2,1 ) * a( 1,2 )

return
end subroutine alcf_coor




! ALCF: original version
subroutine coor(x,y,z,a)
implicit none
real(8),intent(in) :: x,y,z
real(8),intent(out) :: a(3,3)
    
real *8 e(3),r,emin
integer i,imin,imin1,imin2

e(1)=x
e(2)=y
e(3)=z
r=dsqrt(e(1)**2+e(2)**2+e(3)**2) ! NOTE: the second time of normalization, VSemiletov
a(1,1)=e(1)/r
a(2,1)=e(2)/r
a(3,1)=e(3)/r

emin=1e10
imin=0
do i=1,3
    if (emin.gt.dabs(e(i))) then
        emin=dabs(e(i))
        imin=i
        if (abs(emin).lt.1d-10) then ! dangerous reas compare with zero ! NOTE VSemiletov
            a(1,2)=0.0
            a(2,2)=0.0
            a(3,2)=0.0
            a(imin,2)=1.0d0
            goto 1
        end if	
    end if
end do

imin1=imin+1
if (imin1.gt.3) imin1=1
imin2=imin1+1
if (imin2.gt.3) imin2=1
e(imin)=0.0d0
r=e(imin1)
e(imin1)=-e(imin2)
e(imin2)=r

r=dsqrt(e(imin1)**2+e(imin2)**2)

a(1,2)=e(1)/r
a(2,2)=e(2)/r
a(3,2)=e(3)/r

1 continue

a(1,3)=a(2,1)*a(3,2)-a(3,1)*a(2,2)
a(2,3)=a(3,1)*a(1,2)-a(1,1)*a(3,2)
a(3,3)=a(1,1)*a(2,2)-a(2,1)*a(1,2)

return
end subroutine coor
